﻿using System;
using System.Collections.Generic;
using System.Text;

namespace LdCms.BLL.Member
{
    using LdCms.EF.DbModels;
    using LdCms.EF.DbEntitiesContext;
    using LdCms.EF.DbStoredProcedure;
    using LdCms.IBLL.Member;
    using LdCms.IDAL.Member;
    using LdCms.Common.Extension;
    using LdCms.Common.Security;
    using System.Linq;
    using System.Linq.Expressions;
    using LdCms.Common.Utility;

    /// <summary>
    /// 
    /// </summary>
    public partial class InvoiceService:BaseService<Ld_Member_Invoice>,IInvoiceService
    {
        private readonly IInvoiceDAL InvoiceDAL;
        private readonly LdCmsDbEntitiesContext LdCmsDbEntitiesContext;
        public InvoiceService(LdCmsDbEntitiesContext LdCmsDbEntitiesContext, IInvoiceDAL InvoiceDAL)
        {
            this.LdCmsDbEntitiesContext = LdCmsDbEntitiesContext;
            this.InvoiceDAL = InvoiceDAL;
            this.Dal = InvoiceDAL;
        }
        public override void SetDal()
        {
            Dal = InvoiceDAL;
        }

        public bool SaveInvoice(Ld_Member_Invoice entity)
        {
            try
            {
                int systemId = entity.SystemID;
                string companyId = entity.CompanyID;
                string invoiceId = entity.InvoiceID;
                bool isDefault = entity.IsDefault.ToBool();
                bool state = entity.State.ToBool();
                if (string.IsNullOrEmpty(invoiceId))
                {
                    var primarykey = PrimaryKeyHelper.PrimaryKeyType.MemberInvoice;
                    var primaryKeyLen = PrimaryKeyHelper.PrimaryKeyLen.V1;
                    entity.InvoiceID = PrimaryKeyHelper.MakePrimaryKey(primarykey, primaryKeyLen);
                }
                entity.IsDefault = isDefault;
                entity.State = state;
                entity.CreateDate = DateTime.Now;
                int intnum = 0;
                var dbContext = new DAL.BaseDAL(LdCmsDbEntitiesContext);
                using (var db = dbContext.DbEntities())
                {
                    using (var trans = db.Database.BeginTransaction())
                    {
                        try
                        {
                            if (isDefault)
                            {
                                var expression = ExtLinq.True<Ld_Member_Invoice>();
                                expression = expression.And(m => m.SystemID == systemId && m.CompanyID == companyId);
                                var lists = FindList(expression).ToList();
                                lists.ForEach(m => m.IsDefault = false);
                                dbContext.Update(lists);
                            }
                            dbContext.Add(entity);
                            intnum = db.SaveChanges();
                            trans.Commit();
                        }
                        catch (Exception)
                        {
                            trans.Rollback();
                        }
                        return intnum > 0;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public bool UpdateInvoice(Ld_Member_Invoice entity)
        {
            try
            {
                int systemId = entity.SystemID;
                string companyId = entity.CompanyID;
                string invoiceId = entity.InvoiceID;
                bool isDefault = entity.IsDefault.ToBool();
                bool state = entity.State.ToBool();
                entity.IsDefault = isDefault;
                entity.State = state;
                entity.CreateDate = DateTime.Now;
                int intnum = 0;
                var dbContext = new DAL.BaseDAL(LdCmsDbEntitiesContext);
                using (var db = dbContext.DbEntities())
                {
                    using (var trans = db.Database.BeginTransaction())
                    {
                        try
                        {
                            if (isDefault)
                            {
                                var expression = ExtLinq.True<Ld_Member_Invoice>();
                                expression = expression.And(m => m.SystemID == systemId && m.CompanyID == companyId && m.InvoiceID != invoiceId);
                                var lists = FindList(expression).ToList();
                                lists.ForEach(m => m.IsDefault = false);
                                dbContext.Update(lists);
                            }
                            dbContext.Update(entity);
                            intnum = db.SaveChanges();
                            trans.Commit();
                        }
                        catch (Exception)
                        {
                            trans.Rollback();
                        }
                        return intnum > 0;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public bool UpdateInvoiceDefault(int systemId, string companyId, string invoiceId, bool isDefault)
        {
            try
            {
                var entity = Find(m => m.SystemID == systemId && m.CompanyID == companyId && m.InvoiceID == invoiceId);
                if (entity == null)
                    throw new Exception("platform id invalid！");
                entity.IsDefault = isDefault;

                int intnum = 0;
                var dbContext = new DAL.BaseDAL(LdCmsDbEntitiesContext);
                using (var db = dbContext.DbEntities())
                {
                    using (var trans = db.Database.BeginTransaction())
                    {
                        try
                        {
                            if (isDefault)
                            {
                                var expression = ExtLinq.True<Ld_Member_Invoice>();
                                expression = expression.And(m => m.SystemID == systemId && m.CompanyID == companyId && m.InvoiceID != invoiceId);
                                var lists = FindList(expression).ToList();
                                lists.ForEach(m => m.IsDefault = false);
                                dbContext.Update(lists);
                            }
                            dbContext.Update(entity);
                            intnum = db.SaveChanges();
                            trans.Commit();
                        }
                        catch (Exception)
                        {
                            trans.Rollback();
                        }
                        return intnum > 0;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public bool UpdateInvoiceState(int systemId, string companyId, string invoiceId, bool state)
        {
            try
            {
                var entity = Find(m => m.SystemID == systemId && m.CompanyID == companyId && m.InvoiceID == invoiceId);
                if (entity == null)
                    throw new Exception("invoice id invalid！");
                entity.State = state;
                return Update(entity);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public bool DeleteInvoice(int systemId, string companyId, string invoiceId)
        {
            try
            {
                return Delete(m => m.SystemID == systemId && m.CompanyID == companyId && m.InvoiceID == invoiceId);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public Ld_Member_Invoice GetInvoice(int systemId, string companyId, string invoiceId)
        {
            try
            {
                return Find(m => m.SystemID == systemId && m.CompanyID == companyId && m.InvoiceID == invoiceId);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public Ld_Member_Invoice GetInvoiceByDefault(int systemId, string companyId)
        {
            try
            {
                var expression = ExtLinq.True<Ld_Member_Invoice>();
                expression = expression.And(m => m.SystemID == systemId && m.CompanyID == companyId && m.IsDefault == true);
                return FindList(expression, m => m.CreateDate, true).FirstOrDefault();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public List<Ld_Member_Invoice> GetInvoiceAll(int systemId, string companyId)
        {
            try
            {
                var expression = ExtLinq.True<Ld_Member_Invoice>();
                expression = expression.And(m => m.SystemID == systemId && m.CompanyID == companyId);
                return FindList(expression, m => m.IsDefault, false).ToList();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public List<Ld_Member_Invoice> GetInvoiceTop(int systemId, string companyId, int count)
        {
            try
            {
                int total = Utility.ToTopTotal(count);
                var expression = ExtLinq.True<Ld_Member_Invoice>();
                expression = expression.And(m => m.SystemID == systemId && m.CompanyID == companyId);
                var expressionScalarLambda = GetExpressionScalarLambda();
                return FindListTop(expression, expressionScalarLambda, m => m.CreateDate, false, total).ToList();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public List<Ld_Member_Invoice> GetInvoicePaging(int systemId, string companyId, int pageId, int pageSize)
        {
            try
            {
                var expression = ExtLinq.True<Ld_Member_Invoice>();
                expression = expression.And(m => m.SystemID == systemId && m.CompanyID == companyId);
                var expressionScalarLambda = GetExpressionScalarLambda();
                int pageIndex = Utility.ToPageIndex(pageId);
                int pageCount = Utility.ToPageCount(pageSize);
                return FindListPaging(expression, expressionScalarLambda, m => m.CreateDate, false, pageIndex, pageCount).ToList();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public List<Ld_Member_Invoice> SearchInvoice(int systemId, string companyId, string startTime, string endTime, string classId, string keyword, int count)
        {
            try
            {
                DateTime dateStartTime = Utility.ToStartTime(startTime);
                DateTime dateEndTime = Utility.ToEndTime(endTime);
                int intClassId = classId.ToInt();
                int total = Utility.ToTopTotal(count);
                //条件
                var expression = ExtLinq.True<Ld_Member_Invoice>();
                expression = expression.And(m => m.SystemID == systemId && m.CompanyID == companyId
                && m.CreateDate.Value.Date >= dateStartTime.Date && m.CreateDate.Value.Date <= dateEndTime.Date
                && (string.IsNullOrEmpty(classId) ? true : m.ClassID.Value == intClassId)
                && (m.MemberID.Contains(keyword) || m.CompanyName.Contains(keyword)));
                //字段
                var expressionScalarLambda = GetExpressionScalarLambda();
                //执行
                return FindListTop(expression, expressionScalarLambda, m => m.CreateDate, false, total).ToList();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public List<Ld_Member_Invoice> GetInvoicePagingByMemberId(int systemId, string companyId, string memberId, int pageId, int pageSize)
        {
            try
            {
                var expression = ExtLinq.True<Ld_Member_Invoice>();
                expression = expression.And(m => m.SystemID == systemId && m.CompanyID == companyId && m.MemberID == memberId);
                var expressionScalarLambda = GetExpressionScalarLambda();
                int pageIndex = Utility.ToPageIndex(pageId);
                int pageCount = Utility.ToPageCount(pageSize);
                return FindListPaging(expression, expressionScalarLambda, m => m.CreateDate, false, pageIndex, pageCount).ToList();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public int CountInvoice(int systemId, string companyId)
        {
            try
            {
                return Count(m => m.SystemID == systemId && m.CompanyID == companyId);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public int CountInvoice(int systemId, string companyId,string memberId)
        {
            try
            {
                return Count(m => m.SystemID == systemId && m.CompanyID == companyId && m.MemberID == memberId);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public int CountInvoice(int systemId, string companyId, string startTime, string endTime, string classId, string keyword)
        {
            try
            {
                DateTime dateStartTime = Utility.ToStartTime(startTime);
                DateTime dateEndTime = Utility.ToEndTime(endTime);
                int intClassId = classId.ToInt();
                var expression = ExtLinq.True<Ld_Member_Invoice>();
                expression = expression.And(m => m.SystemID == systemId && m.CompanyID == companyId
                && m.CreateDate.Value.Date >= dateStartTime.Date && m.CreateDate.Value.Date <= dateEndTime.Date
                && (string.IsNullOrEmpty(classId) ? true : m.ClassID.Value == intClassId)
                && (m.MemberID.Contains(keyword) || m.CompanyName.Contains(keyword)));
                return Count(expression);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        private Expression<Func<Ld_Member_Invoice, Ld_Member_Invoice>> GetExpressionScalarLambda()
        {
            try
            {
                Expression<Func<Ld_Member_Invoice, Ld_Member_Invoice>> scalarLambda = m => new Ld_Member_Invoice
                {
                    SystemID = m.SystemID,
                    CompanyID = m.CompanyID,
                    InvoiceID = m.InvoiceID,
                    ClassID = m.ClassID,
                    ClassName = m.ClassName,
                    CompanyName = m.CompanyName,
                    TaxpayerIdentificationNumber = m.TaxpayerIdentificationNumber,
                    BankName = m.BankName,
                    BankAccount = m.BankAccount,
                    Tel = m.Tel,
                    Address = m.Address,
                    IsDefault = m.IsDefault,
                    State = m.State,
                    CreateDate = m.CreateDate
                };
                return scalarLambda;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }



    }
}
